{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# cvrp_reload"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/constraint_solver/cvrp_reload.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/ortools/constraint_solver/samples/cvrp_reload.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "Capacitated Vehicle Routing Problem (CVRP).\n",
    "\n",
    "This is a sample using the routing library python wrapper to solve a CVRP\n",
    "problem while allowing multiple trips, i.e., vehicles can return to a depot\n",
    "to reset their load (\"reload\").\n",
    "\n",
    "A description of the CVRP problem can be found here:\n",
    "http://en.wikipedia.org/wiki/Vehicle_routing_problem.\n",
    "\n",
    "Distances are in meters.\n",
    "\n",
    "In order to implement multiple trips, new nodes are introduced at the same\n",
    "locations of the original depots. These additional nodes can be dropped\n",
    "from the schedule at 0 cost.\n",
    "\n",
    "The max_slack parameter associated to the capacity constraints of all nodes\n",
    "can be set to be the maximum of the vehicles' capacities, rather than 0 like\n",
    "in a traditional CVRP. Slack is required since before a solution is found,\n",
    "it is not known how much capacity will be transferred at the new nodes. For\n",
    "all the other (original) nodes, the slack is then re-set to 0.\n",
    "\n",
    "The above two considerations are implemented in `add_capacity_constraints()`.\n",
    "\n",
    "Last, it is useful to set a large distance between the initial depot and the\n",
    "new nodes introduced, to avoid schedules having spurious transits through\n",
    "those new nodes unless it's necessary to reload. This consideration is taken\n",
    "into account in `create_distance_evaluator()`.\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "from functools import partial\n",
    "\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "from ortools.constraint_solver import routing_enums_pb2\n",
    "\n",
    "\n",
    "###########################\n",
    "# Problem Data Definition #\n",
    "###########################\n",
    "def create_data_model():\n",
    "    \"\"\"Stores the data for the problem\"\"\"\n",
    "    data = {}\n",
    "    _capacity = 15\n",
    "    # Locations in block unit\n",
    "    _locations = [\n",
    "        (4, 4),  # depot\n",
    "        (4, 4),  # unload depot_first\n",
    "        (4, 4),  # unload depot_second\n",
    "        (4, 4),  # unload depot_third\n",
    "        (4, 4),  # unload depot_fourth\n",
    "        (4, 4),  # unload depot_fifth\n",
    "        (2, 0),\n",
    "        (8, 0),  # locations to visit\n",
    "        (0, 1),\n",
    "        (1, 1),\n",
    "        (5, 2),\n",
    "        (7, 2),\n",
    "        (3, 3),\n",
    "        (6, 3),\n",
    "        (5, 5),\n",
    "        (8, 5),\n",
    "        (1, 6),\n",
    "        (2, 6),\n",
    "        (3, 7),\n",
    "        (6, 7),\n",
    "        (0, 8),\n",
    "        (7, 8),\n",
    "    ]\n",
    "    # Compute locations in meters using the block dimension defined as follow\n",
    "    # Manhattan average block: 750ft x 264ft -> 228m x 80m\n",
    "    # here we use: 114m x 80m city block\n",
    "    # src: https://nyti.ms/2GDoRIe 'NY Times: Know Your distance'\n",
    "    data[\"locations\"] = [(l[0] * 114, l[1] * 80) for l in _locations]\n",
    "    data[\"num_locations\"] = len(data[\"locations\"])\n",
    "    data[\"demands\"] = [\n",
    "        0,  # depot\n",
    "        -_capacity,  # unload depot_first\n",
    "        -_capacity,  # unload depot_second\n",
    "        -_capacity,  # unload depot_third\n",
    "        -_capacity,  # unload depot_fourth\n",
    "        -_capacity,  # unload depot_fifth\n",
    "        3,\n",
    "        3,  # 1, 2\n",
    "        3,\n",
    "        4,  # 3, 4\n",
    "        3,\n",
    "        4,  # 5, 6\n",
    "        8,\n",
    "        8,  # 7, 8\n",
    "        3,\n",
    "        3,  # 9,10\n",
    "        3,\n",
    "        3,  # 11,12\n",
    "        4,\n",
    "        4,  # 13, 14\n",
    "        8,\n",
    "        8,\n",
    "    ]  # 15, 16\n",
    "    data[\"time_per_demand_unit\"] = 5  # 5 minutes/unit\n",
    "    data[\"time_windows\"] = [\n",
    "        (0, 0),  # depot\n",
    "        (0, 1000),  # unload depot_first\n",
    "        (0, 1000),  # unload depot_second\n",
    "        (0, 1000),  # unload depot_third\n",
    "        (0, 1000),  # unload depot_fourth\n",
    "        (0, 1000),  # unload depot_fifth\n",
    "        (75, 850),\n",
    "        (75, 850),  # 1, 2\n",
    "        (60, 700),\n",
    "        (45, 550),  # 3, 4\n",
    "        (0, 800),\n",
    "        (50, 600),  # 5, 6\n",
    "        (0, 1000),\n",
    "        (10, 200),  # 7, 8\n",
    "        (0, 1000),\n",
    "        (75, 850),  # 9, 10\n",
    "        (85, 950),\n",
    "        (5, 150),  # 11, 12\n",
    "        (15, 250),\n",
    "        (10, 200),  # 13, 14\n",
    "        (45, 550),\n",
    "        (30, 400),\n",
    "    ]  # 15, 16\n",
    "    data[\"num_vehicles\"] = 3\n",
    "    data[\"vehicle_capacity\"] = _capacity\n",
    "    data[\"vehicle_max_distance\"] = 10_000\n",
    "    data[\"vehicle_max_time\"] = 1_500\n",
    "    data[\"vehicle_speed\"] = 5 * 60 / 3.6  # Travel speed: 5km/h to convert in m/min\n",
    "    data[\"depot\"] = 0\n",
    "    return data\n",
    "\n",
    "\n",
    "#######################\n",
    "# Problem Constraints #\n",
    "#######################\n",
    "def manhattan_distance(position_1, position_2):\n",
    "    \"\"\"Computes the Manhattan distance between two points\"\"\"\n",
    "    return abs(position_1[0] - position_2[0]) + abs(position_1[1] - position_2[1])\n",
    "\n",
    "\n",
    "def create_distance_evaluator(data):\n",
    "    \"\"\"Creates callback to return distance between points.\"\"\"\n",
    "    _distances = {}\n",
    "    # precompute distance between location to have distance callback in O(1)\n",
    "    for from_node in range(data[\"num_locations\"]):\n",
    "        _distances[from_node] = {}\n",
    "        for to_node in range(data[\"num_locations\"]):\n",
    "            if from_node == to_node:\n",
    "                _distances[from_node][to_node] = 0\n",
    "            # Forbid start/end/reload node to be consecutive.\n",
    "            elif from_node in range(6) and to_node in range(6):\n",
    "                _distances[from_node][to_node] = data[\"vehicle_max_distance\"]\n",
    "            else:\n",
    "                _distances[from_node][to_node] = manhattan_distance(\n",
    "                    data[\"locations\"][from_node], data[\"locations\"][to_node]\n",
    "                )\n",
    "\n",
    "    def distance_evaluator(manager, from_node, to_node):\n",
    "        \"\"\"Returns the manhattan distance between the two nodes\"\"\"\n",
    "        return _distances[manager.IndexToNode(from_node)][manager.IndexToNode(to_node)]\n",
    "\n",
    "    return distance_evaluator\n",
    "\n",
    "\n",
    "def add_distance_dimension(routing, manager, data, distance_evaluator_index):\n",
    "    \"\"\"Add Global Span constraint\"\"\"\n",
    "    del manager\n",
    "    distance = \"Distance\"\n",
    "    routing.AddDimension(\n",
    "        distance_evaluator_index,\n",
    "        0,  # null slack\n",
    "        data[\"vehicle_max_distance\"],  # maximum distance per vehicle\n",
    "        True,  # start cumul to zero\n",
    "        distance,\n",
    "    )\n",
    "    distance_dimension = routing.GetDimensionOrDie(distance)\n",
    "    # Try to minimize the max distance among vehicles.\n",
    "    # /!\\ It doesn't mean the standard deviation is minimized\n",
    "    distance_dimension.SetGlobalSpanCostCoefficient(100)\n",
    "\n",
    "\n",
    "def create_demand_evaluator(data):\n",
    "    \"\"\"Creates callback to get demands at each location.\"\"\"\n",
    "    _demands = data[\"demands\"]\n",
    "\n",
    "    def demand_evaluator(manager, from_node):\n",
    "        \"\"\"Returns the demand of the current node\"\"\"\n",
    "        return _demands[manager.IndexToNode(from_node)]\n",
    "\n",
    "    return demand_evaluator\n",
    "\n",
    "\n",
    "def add_capacity_constraints(routing, manager, data, demand_evaluator_index):\n",
    "    \"\"\"Adds capacity constraint\"\"\"\n",
    "    vehicle_capacity = data[\"vehicle_capacity\"]\n",
    "    capacity = \"Capacity\"\n",
    "    routing.AddDimension(\n",
    "        demand_evaluator_index,\n",
    "        vehicle_capacity,\n",
    "        vehicle_capacity,\n",
    "        True,  # start cumul to zero\n",
    "        capacity,\n",
    "    )\n",
    "\n",
    "    # Add Slack for reseting to zero unload depot nodes.\n",
    "    # e.g. vehicle with load 10/15 arrives at node 1 (depot unload)\n",
    "    # so we have CumulVar = 10(current load) + -15(unload) + 5(slack) = 0.\n",
    "    capacity_dimension = routing.GetDimensionOrDie(capacity)\n",
    "    # Allow to drop reloading nodes with zero cost.\n",
    "    for node in [1, 2, 3, 4, 5]:\n",
    "        node_index = manager.NodeToIndex(node)\n",
    "        routing.AddDisjunction([node_index], 0)\n",
    "\n",
    "    # Allow to drop regular node with a cost.\n",
    "    for node in range(6, len(data[\"demands\"])):\n",
    "        node_index = manager.NodeToIndex(node)\n",
    "        capacity_dimension.SlackVar(node_index).SetValue(0)\n",
    "        routing.AddDisjunction([node_index], 100_000)\n",
    "\n",
    "\n",
    "def create_time_evaluator(data):\n",
    "    \"\"\"Creates callback to get total times between locations.\"\"\"\n",
    "\n",
    "    def service_time(data, node):\n",
    "        \"\"\"Gets the service time for the specified location.\"\"\"\n",
    "        return abs(data[\"demands\"][node]) * data[\"time_per_demand_unit\"]\n",
    "\n",
    "    def travel_time(data, from_node, to_node):\n",
    "        \"\"\"Gets the travel times between two locations.\"\"\"\n",
    "        if from_node == to_node:\n",
    "            travel_time = 0\n",
    "        else:\n",
    "            travel_time = (\n",
    "                manhattan_distance(\n",
    "                    data[\"locations\"][from_node], data[\"locations\"][to_node]\n",
    "                )\n",
    "                / data[\"vehicle_speed\"]\n",
    "            )\n",
    "        return travel_time\n",
    "\n",
    "    _total_time = {}\n",
    "    # precompute total time to have time callback in O(1)\n",
    "    for from_node in range(data[\"num_locations\"]):\n",
    "        _total_time[from_node] = {}\n",
    "        for to_node in range(data[\"num_locations\"]):\n",
    "            if from_node == to_node:\n",
    "                _total_time[from_node][to_node] = 0\n",
    "            else:\n",
    "                _total_time[from_node][to_node] = int(\n",
    "                    service_time(data, from_node)\n",
    "                    + travel_time(data, from_node, to_node)\n",
    "                )\n",
    "\n",
    "    def time_evaluator(manager, from_node, to_node):\n",
    "        \"\"\"Returns the total time between the two nodes\"\"\"\n",
    "        return _total_time[manager.IndexToNode(from_node)][manager.IndexToNode(to_node)]\n",
    "\n",
    "    return time_evaluator\n",
    "\n",
    "\n",
    "def add_time_window_constraints(routing, manager, data, time_evaluator):\n",
    "    \"\"\"Add Time windows constraint\"\"\"\n",
    "    time = \"Time\"\n",
    "    max_time = data[\"vehicle_max_time\"]\n",
    "    routing.AddDimension(\n",
    "        time_evaluator,\n",
    "        max_time,  # allow waiting time\n",
    "        max_time,  # maximum time per vehicle\n",
    "        False,  # don't force start cumul to zero since we are giving TW to start nodes\n",
    "        time,\n",
    "    )\n",
    "    time_dimension = routing.GetDimensionOrDie(time)\n",
    "    # Add time window constraints for each location except depot\n",
    "    # and 'copy' the slack var in the solution object (aka Assignment) to print it\n",
    "    for location_idx, time_window in enumerate(data[\"time_windows\"]):\n",
    "        if location_idx == 0:\n",
    "            continue\n",
    "        index = manager.NodeToIndex(location_idx)\n",
    "        time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])\n",
    "        routing.AddToAssignment(time_dimension.SlackVar(index))\n",
    "    # Add time window constraints for each vehicle start node\n",
    "    # and 'copy' the slack var in the solution object (aka Assignment) to print it\n",
    "    for vehicle_id in range(data[\"num_vehicles\"]):\n",
    "        index = routing.Start(vehicle_id)\n",
    "        time_dimension.CumulVar(index).SetRange(\n",
    "            data[\"time_windows\"][0][0], data[\"time_windows\"][0][1]\n",
    "        )\n",
    "        routing.AddToAssignment(time_dimension.SlackVar(index))\n",
    "        # Warning: Slack var is not defined for vehicle's end node\n",
    "        # routing.AddToAssignment(time_dimension.SlackVar(self.routing.End(vehicle_id)))\n",
    "\n",
    "\n",
    "###########\n",
    "# Printer #\n",
    "###########\n",
    "def print_solution(\n",
    "    data, manager, routing, assignment\n",
    "):  # pylint:disable=too-many-locals\n",
    "    \"\"\"Prints assignment on console\"\"\"\n",
    "    print(f\"Objective: {assignment.ObjectiveValue()}\")\n",
    "    total_distance = 0\n",
    "    total_load = 0\n",
    "    total_time = 0\n",
    "    capacity_dimension = routing.GetDimensionOrDie(\"Capacity\")\n",
    "    time_dimension = routing.GetDimensionOrDie(\"Time\")\n",
    "    distance_dimension = routing.GetDimensionOrDie(\"Distance\")\n",
    "    dropped = []\n",
    "    for order in range(6, routing.nodes()):\n",
    "        index = manager.NodeToIndex(order)\n",
    "        if assignment.Value(routing.NextVar(index)) == index:\n",
    "            dropped.append(order)\n",
    "    print(f\"dropped orders: {dropped}\")\n",
    "    dropped = []\n",
    "    for reload in range(1, 6):\n",
    "        index = manager.NodeToIndex(reload)\n",
    "        if assignment.Value(routing.NextVar(index)) == index:\n",
    "            dropped.append(reload)\n",
    "    print(f\"dropped reload stations: {dropped}\")\n",
    "\n",
    "    for vehicle_id in range(data[\"num_vehicles\"]):\n",
    "        if not routing.IsVehicleUsed(assignment, vehicle_id):\n",
    "            continue\n",
    "        index = routing.Start(vehicle_id)\n",
    "        plan_output = f\"Route for vehicle {vehicle_id}:\\n\"\n",
    "        load_value = 0\n",
    "        distance = 0\n",
    "        while not routing.IsEnd(index):\n",
    "            time_var = time_dimension.CumulVar(index)\n",
    "            plan_output += (\n",
    "                f\" {manager.IndexToNode(index)} \"\n",
    "                f\"Load({assignment.Min(capacity_dimension.CumulVar(index))}) \"\n",
    "                f\"Time({assignment.Min(time_var)},{assignment.Max(time_var)}) ->\"\n",
    "            )\n",
    "            previous_index = index\n",
    "            index = assignment.Value(routing.NextVar(index))\n",
    "            distance += distance_dimension.GetTransitValue(previous_index, index, vehicle_id)\n",
    "            # capacity dimension TransitVar is negative at reload stations during replenishment\n",
    "            # don't want to consider those values when calculating the total load of the route\n",
    "            # hence only considering the positive values\n",
    "            load_value += max(0, capacity_dimension.GetTransitValue(previous_index, index, vehicle_id))\n",
    "        time_var = time_dimension.CumulVar(index)\n",
    "        plan_output += (\n",
    "            f\" {manager.IndexToNode(index)} \"\n",
    "            f\"Load({assignment.Min(capacity_dimension.CumulVar(index))}) \"\n",
    "            f\"Time({assignment.Min(time_var)},{assignment.Max(time_var)})\\n\"\n",
    "        )\n",
    "        plan_output += f\"Distance of the route: {distance}m\\n\"\n",
    "        plan_output += f\"Load of the route: {load_value}\\n\"\n",
    "        plan_output += f\"Time of the route: {assignment.Min(time_var)}min\\n\"\n",
    "        print(plan_output)\n",
    "        total_distance += distance\n",
    "        total_load += load_value\n",
    "        total_time += assignment.Min(time_var)\n",
    "    print(f\"Total Distance of all routes: {total_distance}m\")\n",
    "    print(f\"Total Load of all routes: {total_load}\")\n",
    "    print(f\"Total Time of all routes: {total_time}min\")\n",
    "\n",
    "\n",
    "########\n",
    "# Main #\n",
    "########\n",
    "def main():\n",
    "    \"\"\"Entry point of the program\"\"\"\n",
    "    # Instantiate the data problem.\n",
    "    data = create_data_model()\n",
    "\n",
    "    # Create the routing index manager\n",
    "    manager = pywrapcp.RoutingIndexManager(\n",
    "        data[\"num_locations\"], data[\"num_vehicles\"], data[\"depot\"]\n",
    "    )\n",
    "\n",
    "    # Create Routing Model\n",
    "    routing = pywrapcp.RoutingModel(manager)\n",
    "\n",
    "    # Define weight of each edge\n",
    "    distance_evaluator_index = routing.RegisterTransitCallback(\n",
    "        partial(create_distance_evaluator(data), manager)\n",
    "    )\n",
    "    routing.SetArcCostEvaluatorOfAllVehicles(distance_evaluator_index)\n",
    "\n",
    "    # Add Distance constraint to minimize the longuest route\n",
    "    add_distance_dimension(routing, manager, data, distance_evaluator_index)\n",
    "\n",
    "    # Add Capacity constraint\n",
    "    demand_evaluator_index = routing.RegisterUnaryTransitCallback(\n",
    "        partial(create_demand_evaluator(data), manager)\n",
    "    )\n",
    "    add_capacity_constraints(routing, manager, data, demand_evaluator_index)\n",
    "\n",
    "    # Add Time Window constraint\n",
    "    time_evaluator_index = routing.RegisterTransitCallback(\n",
    "        partial(create_time_evaluator(data), manager)\n",
    "    )\n",
    "    add_time_window_constraints(routing, manager, data, time_evaluator_index)\n",
    "\n",
    "    # Setting first solution heuristic (cheapest addition).\n",
    "    search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
    "    search_parameters.first_solution_strategy = (\n",
    "        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC\n",
    "    )  # pylint: disable=no-member\n",
    "    search_parameters.local_search_metaheuristic = (\n",
    "        routing_enums_pb2.LocalSearchMetaheuristic.GUIDED_LOCAL_SEARCH\n",
    "    )\n",
    "    search_parameters.time_limit.FromSeconds(3)\n",
    "\n",
    "    # Solve the problem.\n",
    "    solution = routing.SolveWithParameters(search_parameters)\n",
    "    if solution:\n",
    "        print_solution(data, manager, routing, solution)\n",
    "    else:\n",
    "        print(\"No solution found !\")\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
